package com.msxt.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL) {

            protected String optimizeCountSql(String originalSql) {
                // 1. 移除ORDER BY子句
                String countSql = originalSql.replaceAll("(?i)ORDER\\s+BY\\s+[^)]+$", "");

                // 2. 修复WHERE条件中的1=1问题
                countSql = countSql.replaceAll("WHERE\\s+1=1\\s*AND", "WHERE");

                // 3. 确保WHERE后面没有空条件
                if (countSql.contains("WHERE ")) {
                    String wherePart = countSql.substring(countSql.indexOf("WHERE "));
                    if (wherePart.trim().equals("WHERE") || wherePart.trim().equals("WHERE ")) {
                        countSql = countSql.substring(0, countSql.indexOf("WHERE "));
                    }
                }

                return "SELECT COUNT(*) FROM (" + countSql + ") mp_count";
            }
        };

        paginationInnerInterceptor.setMaxLimit(1000L);
        paginationInnerInterceptor.setOptimizeJoin(false);

        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }
}